<?php

namespace app\api\logic;
use app\api\logic\TestLogic;
use app\data\util\MqQueueName;
use app\purchase\logic\PlanSuggestLogic;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Cache;
use think\facade\Db;
use app\data\util\HttpUtil;
use  app\api\logic\FreightLogic;
use  app\api\logic\LinXingOrderLogic;
use  app\order\logic\OrderLogic;
use  app\order\logic\CheckbillLogic;
use app\api\logic\ApiOrderLogic;

class CheckLogic extends BasicLogic
{

    /**
     * @desc    产品图片迁移到杭州
     * @author  luckyXiong
     * @date    2024-10-11
     */
    public function remove_image(){
        $t1         = microtime(true);
        $field    = 'order_id,sku,order_number as honey_order_number,shop_name,num,buyer_name,buyer_email,address,city,state,post_code,phone,country,create_time';
        $where    = [];
        $order_ids = [];
        $where[]  = ['order_number','in',$order_ids];
        $time_start = date('Y-m-d 00:00:00');
        $time_end   = date('Y-m-d 23:59:59');
        $where[]    = ['create_time','between', [$time_start, $time_end]];
        $list       = Db::name('order_history_list')->field($field)->where($where)->select()->toArray();
        $count      = count($list);
        $executedCount =0;
        foreach ($list as $k=>$v){
            echo PHP_EOL ."执行第:" . ($k+1) ."条".PHP_EOL;
            $skus = explode('+',$v['sku']);
            $sku_info = implode(',',$skus);
            $update= [
                'sku'  => $sku_info,
            ];
            $check_res      =(new TestLogic)->get_inventory_hwc($skus);
            if($check_res){
                $update['ship_status']       = 8;
                $update['warehouse_id_plan'] = $check_res;
            }
            Db::name('order_shopify_list')->where('honey_order_number',$v['honey_order_number'])->update($update);
            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
        echo PHP_EOL . "get_spu_fee-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }


    /**
     * @desc    更新访问产品页面的spu数据
     * @author  luckyXiong
     * @date    2025-04-25
     */
    public function edit_path_spu(){
        $t1         = microtime(true);
        $field      = 'shop_id,spu,product_shopify_id,seo_title';
        $where      = [];
        $where[]    = ['spu','<>',''];
        $list       = Db::name('listing_shop_product')->field($field)->where($where)->select()->toArray();
        $count      = count($list);
        $executedCount = 0;
        foreach ($list as $v){
         /*   $parts      = explode('+', $v['sku']);
            $spu_info   = explode('-', $parts[0]);
            $spu        = $spu_info[0]??'';*/
            $update = [
                    'shop_id'    =>$v['shop_id'],
                    'product_id' =>$v['product_shopify_id'],
                    'page_path'  =>$v['seo_title'] ? '/products/'.$v['seo_title']:'',
                    'spu'        =>$v['spu'],
                    'create_time'=>date("Y-m-d H:i:s", time()),
            ];
            Db::name('order_page_visits_product')->insert($update);
            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
        echo PHP_EOL . "get_spu_fee-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }


    /**
     * @desc    更新访问产品页面的spu数据
     * @author  luckyXiong
     * @date    2025-04-25
     */
    public function update_sku_size(){
        $t1         = microtime(true);
        $field      = 'id';
        $where      = [];
        $lists      = Db::name('order_skuinfo')->field($field)->where($where)->select()->toArray();
        $count      = count($lists);
        $executedCount= 0;
        $pageSize     = 500;
        $page         = ceil($count / $pageSize);
        $arr          = [];
        try{
            for ($i = 1; $i <= $page; $i++){
                $list   = Db::name('order_skuinfo')
                    ->field('id,spu,sku')
                    ->limit(($i - 1) * $pageSize, $pageSize)
                    ->select();
                $list = objectToArray($list);
                foreach($list as $v){
                    $arr = self::get_sku_info($v);
                    $executedCount++;
                    $num = $count - $executedCount;
                    echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
                }
                Db::name('order_sku_size')->insertAll($arr);
                echo PHP_EOL . '执行第' .($i*500).'条'. PHP_EOL;
            }
        }catch (\Exception $e) {
            echo  $e->getMessage();
            return error('失败:' . $e->getMessage());
        }

        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }



    /**
     * @desc    更新访问产品页面的spu数据
     * @author  luckyXiong
     * @date    2025-04-25
     */
    public function wash_sku_size(){
        $t1       = microtime(true);
        $where   = [];
        $where[] = ['video_file','<>',''];
        $where[] = ['storage_url','=',''];
        $where[] = ['id','<>','176'];
        $where[] = ['expert_name','<>','affordablestylesnicole'];
        $field   = 'id,video_file';
        $executedCount = 0;
        $list    = Db::name('tik_kol_video')->field($field)->where($where)->select()->toArray();
        $count   = count($list);
        try{
            foreach($list as $v){
                $video_file                 = json_decode($v['video_file'],true);
                $message_info['video_id']   = $v['id'];
                $message_info['video_file'] = $video_file;
                (new KolMessageLogic())->video_local_consumer($message_info);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }

        }catch (\Exception $e) {
            echo  $e->getMessage();
            return error('失败:' . $e->getMessage());
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }






    private function get_sku_info($info){
        $spu  = $info['spu']??'';
        $data = [];
        //查看产品类型;
        $product_type = (new LinXingOrderLogic())->get_product_type(['spu'=>$spu]);
        if(strpos($info['sku'], '+') !== false){
            $parts        = self::get_sku_infos(['SKU'=>$info['sku'],'num'=>$info['quantity']]);
            foreach($parts as $v){
                $temp =  [
                    'spu'         => $spu,
                    'seller_sku'  => $v['SKU']??'',
                    'color'       => $sizeinfo['color']??'',
                    'size'        => $sizeinfo['size']??'',
                    'cup'         => $sizeinfo['cup']??'',
                    'create_time' => date("Y-m-d H:i:s",time()),
                ];
                $data[] = $temp;
            }
        }else{
            $temp =  [
                'spu'         => $spu,
                'seller_sku'  => $info['sku']??'',
                'color'       => $sizeinfo['color']??'',
                'size'        => $sizeinfo['size']??'',
                'cup'         => $sizeinfo['cup']??'',
                'create_time' => date("Y-m-d H:i:s",time()),
            ];
            $data[] = $temp;
        }
        return $data;
    }


    private function get_seller_info($info){
        $spu  = $info['spu']??'';
        $data = [];
        $order_info   = Db::name('order')->field('order_id,shop_id,financial_status,fulfillment_status,createtime')
                        ->where('order_id',$info['order_id'])
                        ->find();
        if(strpos($info['sku'], '+') !== false){
            $parts        = self::get_sku_infos(['SKU'=>$info['sku'],'num'=>$info['quantity']]);
            foreach($parts as $v){
                $temp =  [
                    'shop_id'           => $info['shop_id']??'',
                    'order_id'          => $info['order_id']??'',
                    'product_id'        => $info['product_id']??'',
                    'sku'               => $info['sku']??'',
                    'new_sku'           => $v['SKU']??'',
                    'spu'               => $spu,
                    'financial_status'  => $order_info['financial_status']??'',
                    'fulfillment_status'=> $order_info['fulfillment_status']??'',
                    'createtime'        => $order_info['createtime']??'',
                    'realcount'         => $parts['num']??'1',
                    'create_time'       => date("Y-m-d H:i:s",time()),
                ];
                $data[] = $temp;
            }
        }else{
            $temp =  [
                'shop_id'           => $info['shop_id']??'',
                'order_id'          => $info['order_id']??'',
                'product_id'        => $info['product_id']??'',
                'sku'               => $info['sku']??'',
                'new_sku'           => $info['sku']??'',
                'spu'               => $spu,
                'financial_status'  => $order_info['financial_status']??'',
                'fulfillment_status'=> $order_info['fulfillment_status']??'',
                'createtime'        => $order_info['createtime']??'',
                'realcount'         => $info['quantity']??'1',
                'create_time'       => date("Y-m-d H:i:s",time()),
            ];
            $data[] = $temp;
        }
        return $data;
    }



    /**
     * @desc    获取详情信息
     * @author  luckyXiong
     * @date    2024-12-11
     */
    public function get_track_info($info){
        $track_number = $info['track_number']??'';
        $order_id     = $info['order_id']??'';
        $shop_id      = $info['shop_id']??'';
        $list         = (new CheckbillLogic())->get_track_info($track_number);
        $insert_data =  [
            'order_id'         =>$order_id,
            'shop_id'          =>$shop_id,
            'track_number'     =>$track_number,
            'provider_country' =>$list['provider_country']??'US',
            'provider_name'    =>$list['provider_name']??'',
            'receive_country'  =>$list['receive_country']??'US',
            'latest_status'    =>$list['latest_status']??'',
            'latest_sub_status'=>$list['latest_sub_status']??'',
            'tracking_list'    =>$list['tracking_list'] ? json_encode($list['tracking_list']) : '',
            'update_time'      =>date("Y-m-d H:i:s", time()),
            'create_time'      =>date("Y-m-d H:i:s", time()),
        ];

        $update_data = [
            'provider_country' =>$list['provider_country']??'US',
            'provider_name'    =>$list['provider_name']??'',
            'receive_country'  =>$list['receive_country']??'US',
            'latest_status'    =>$list['latest_status']??'',
            'latest_sub_status'=>$list['latest_sub_status']??'',
            'tracking_list'    =>$list['tracking_list'] ? json_encode($list['tracking_list']) : '',
            'update_time'      =>date("Y-m-d H:i:s", time()),
        ];

        Db::name('order_track')->where(['track_number'=>$track_number])->update($update_data);


     /*   $exist_info = Db::name('order_track')->field('id,order_id,shop_id,track_number')->where(['track_number'=>$track_number])->find();
        if(empty($exist_info)){
              Db::name('order_track')->insert($insert_data);
        }else{
              Db::name('order_track')->where(['id'=>$exist_info['id']])->update($update_data);
        }*/
        return  true;
    }


    public function get_sku_infos($originalArray){
        // Split the SKU into parts
        $skuParts = explode('-', $originalArray['SKU']);
        $colorParts = explode('+', $skuParts[1]);
        // Count occurrences of each color
        $colorCounts = array_count_values($colorParts);
        // Create the new arrays
        $newArray = array();
        $sku_last = $skuParts[2]??'';
        foreach ($colorCounts as $color => $count) {
            $newArray[] = array(
                'num' => $originalArray['num'] * $count,
                'SKU' => $skuParts[0] . '-' . $color . '-' . $sku_last
            );
        }
        return $newArray;
    }



    /**
     * @desc    产品图片更新
     * @author  luckyXiong
     * @date    2024-10-12
     */
    private function change_images($arr){
        $info = [];
        foreach($arr as $v){
            $value  = str_replace("yltiktok.oss-cn-hongkong", "cntiktok.oss-cn-hangzhou", $v);
            $info[] = $value;
        }
        return  json_encode($info);
    }

    /**
     * @desc    获取供应链接
     * @author  luckyXiong
     * @date    2024-10-21
     */
    private function get_source_link($spu){
        $list  = Db::name('supply_info')->field('id,spu')->where(['spu'=>$spu])->select();
        $list  = objectToArray($list);
        $ids   = array_column($list,'id');
        if($ids){
            $ids = implode(',',$ids);
        }else{
            $ids = '';
        }
        return  $ids;
    }



    /**
     * @desc    空中云慧数据获取
     * @author  luckyXiong
     * @date    2024-10-19
     */
    public function get_airwallex_info($params=[]){
        $token       = self::get_token();
        $page_after  = $params['page_after']??'';
        $basic_url   = Config('Logisticskey.airwallex.basic_url');
        $login_url   = Config('Logisticskey.airwallex.dispute_url');
        $url         = $basic_url.$login_url;
        $key         = 'airwallex_token';
        if($page_after){
            $url = $url.'?page='.$page_after;
        }
        $info        = HttpUtil::getUrlshopline($url,['app_secret'=>$token]);
        if(isset($info['code']) && $info['code']=='unauthorized'){
            Cache::store('redis')->delete($key);
            $token       = self::get_token();
            $info        = HttpUtil::getUrlshopline($url,['app_secret'=>$token]);
        }
        // 数据入库;
        $list  = $info['items']??[];
        $page  = $info['page_after']??'';
        if(!$list || !$page)  return  '赞无数据!';
        $arr = [];
        foreach($list as $v){
            $arr[] = self::insert_airwallex_info($v);
        }
        Db::name('order_dispute_airwallex')->insertAll($arr);
        return $page;
    }


    public function get_webhook_test($message){
        return (new WebhookLogic())->orders_creates_consumer($message);

    }




    /**
     * @desc    空中云慧数据获取
     * @author  luckyXiong
     * @date    2024-10-19
     */
    public function get_airwallex_list(){
        // $token       = self::get_token();
        // $basic_url   = Config('Logisticskey.airwallex.basic_url');
        // $login_url   = Config('Logisticskey.airwallex.dispute_url');
        // $url         = $basic_url.$login_url."?size=1000";
        // $key         = 'airwallex_token';
        // $info        = HttpUtil::getUrlshopline($url,['app_secret'=>$token]);
        // if(isset($info['code']) && $info['code']=='unauthorized'){
        //     Cache::store('redis')->delete($key);
        //     $token       = self::get_token();
        //     $info        = HttpUtil::getUrlshopline($url,['app_secret'=>$token]);
        // }
        // // 数据入库;
        // $list  = $info['items']??[];
        // $page  = $info['page_before']??'';
        // if(!$list)  return  '赞无数据!';
        // $arr = [];
        // foreach($list as $v){
        //     $arr[] = self::insert_airwallex_info($v);
        //     Db::name('order_dispute_airwallex')->where('airwallex_id',$v['id'])->delete();
        // }
        // Db::name('order_dispute_airwallex')->insertAll($arr);
        // return $page;
    }


    /**
     * @desc    空中云慧数据获取
     * @author  luckyXiong
     * @date    2024-10-19
     */
    public function get_token(){
        $key         = 'airwallex_token';
        $token       = Cache::store('redis')->get($key);
        if(empty($token)){
            $merchantId  = Config('Logisticskey.airwallex.merchantId');
            $merchantKey = Config('Logisticskey.airwallex.merchantKey');
            $basic_url   = Config('Logisticskey.airwallex.basic_url');
            $login_url   = Config('Logisticskey.airwallex.login_url');
            $url         = $basic_url.$login_url;
            $data        = [
                'merchantId' =>$merchantId,
                'merchantKey'=>$merchantKey,
            ];
            $response  =  HttpUtil::getAirwallexUrlToken($url,$data);
            $token     =  $response['token']??'';
            $expire    =  strtotime($response['expires_at']);
            Cache::store('redis')->set($key, $token,$expire-3);
        }
        return  $token;

    }

    /**
     * @desc    空中云慧数据获取
     * @author  luckyXiong
     * @date    2024-10-19
     */
    private function insert_airwallex_info($info=[]){
        $merchant_order_id = $info['merchant_order_id'];
        $order_id = Db::name('order_transactions')->where(['payment_id'=>$merchant_order_id])->value('order_id');
        $orderId  = $order_id ?:'';
        $airwallex_status = Config('Logisticskey.airwallex_status');
        $status_cn = $airwallex_status[$info['status']]??'';
        $data = [
            'airwallex_id'       =>$info['id'],
            'order_id'           =>$orderId,
            'payment_order_id'   =>$merchant_order_id,
            'payment_intent_id'  =>$info['payment_intent_id'],
            'payment_attempt_id' =>$info['payment_attempt_id'],
            'payment_method_type'=>$info['payment_method_type'],
            'stage'              =>$info['stage'],
            'status'             =>$info['status'],
            'status_cn'          =>$status_cn,
            'due_at'             =>$info['due_at']     ? date("Y-m-d H:i:s", strtotime($info['due_at'])) : '',
            'created_at'         =>$info['created_at'] ? date("Y-m-d H:i:s", strtotime($info['created_at'])) : '',
            'updated_at'         =>$info['updated_at'] ? date("Y-m-d H:i:s", strtotime($info['updated_at'])) : '',
        ];
        return $data;
    }


    /**
     * @desc
     * @author  luckyXiong
     * @date    2024-10-29
     */
    public function get_count_inventory(){
        $t1         = microtime(true);
        $where      = [];
        $where[]    = ['purchase_code','<>',''];
        $list       = Db::name('purchase_inventory')->field('id,spu,real_delivery_nums,purchase_code,contract_number')->where($where)->select()->toArray();
        $count      = count($list);
        $executedCount =0;
        foreach ($list as $k=>$v){
            echo PHP_EOL ."执行第:" . ($k+1) ."条".PHP_EOL;
            $field          = 'inventory_quantity,on_way_quantity,not_send_quantity,buy_inventory_quantity';
            $info           = Db::name('product_inventory')->where('purchase_number',$v['purchase_code'])->field($field)->select();
            $info           = objectToArray($info);
            if(!$info)        continue;
            $on_travel_nums   = array_sum(array_column($info,'on_way_quantity'));
            $un_send_nums     = array_sum(array_column($info,'not_send_quantity'));
            $inventory_nums   = array_sum(array_column($info,'inventory_quantity'));
            $total_order_nums = array_sum(array_column($info,'buy_inventory_quantity'));
            $defective_rate   = Db::name('purchase_pants_inventory')->where(['purchase_code'=>$v['purchase_code'],'spu'=>$v['spu']])->value('defective_rate');
            $data= [
                'purchase_code'    => $v['purchase_code'],
                'contract_number'  => $v['contract_number'],
                'spu'              => $v['spu'],
                'on_travel_nums'   => $on_travel_nums ?:0,
                'un_send_nums'     => $un_send_nums?:0,
                'inventory_nums'   => $inventory_nums?:0,
                'delivery_nums'    => $v['real_delivery_nums']??0,
                'total_order_nums' => $total_order_nums?:0,
                'create_time'      => date("Y-m-d H:i:s", time()),
            ];
            if($defective_rate){
                $data['defective_rate'] = $defective_rate;
            }
            $exist_info = Db::name('purchase_count_inventory')->where('purchase_code',$v['purchase_code'])->find();
            if(!$exist_info){
                Db::name('purchase_count_inventory')->insert($data);
            }
            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }
        echo PHP_EOL . "get_spu_fee-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }


    public function change_weight(){
        $t1       = microtime(true);
        $count    = Db::name('checkbill_888')->field('*')->count();
        $executedCount = 0;
        $list     = Db::name('checkbill_888')->field('*')->select()->toArray();
        try{
            foreach ($list as $v){
                $sku_list           = self::change_skus($v['sku']);
                Db::name('checkbill_999')->insertAll($sku_list);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
            echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        }catch (\Exception $e) {
            echo  $e->getMessage();
            return error('失败:' . $e->getMessage());
        }
    }


    public function get_webhook_infos2(){
        $t1           = microtime(true);
        $where        = [];
        $where[]      = ['shop_id','<>',''];
        $where[]      = ['type','=','1'];
        $where[]      = ['track_number', 'not like', '%' . 'AT' . '%'];
        $where[]      = ['track_number', 'not like', '%' . 'AM' . '%'];
        $where[]      = ['track_number', 'not like', '%' . 'LZ' . '%'];
        $count        = Db::name('order_track')->whereNull('latest_time')->where($where)->field('order_id,shop_id')->count();
        $executedCount= 0;
        $pageSize     = 10;
        $page         = ceil($count / $pageSize);
        for ($i = 1; $i <= $page; $i++){
            $list   = Db::name('order_track')
                ->where($where)
                ->whereNull('latest_time')
                ->field('order_id,shop_id,track_number')
                ->limit(($i - 1) * $pageSize, $pageSize)
                ->select();
            $list = objectToArray($list);
            $arr =[];
            foreach($list as $v){
                //推动数据到队列;
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_ORDER_TRACK_17_QUEUE,
                    $v,
                    false
                );
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
            Db::name('order_track')->insertAll($arr);
            echo PHP_EOL . '执行第' .($i*500).'条'. PHP_EOL;
        }

        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }


    public function get_webhook_infos(){
        $t1           = microtime(true);
        $where        = [];
        $time_start   = '1740787270';
        $time_end     = '1743415270';
        $where[]      = ['createtime','between', [$time_start, $time_end]];
        $where[]      = ['financial_status','=','paid'];
        $count        = Db::name('order')->where($where)->field('id,order_id')->count();
        $executedCount= 0;
        $pageSize     = 500;
        //$page         = ceil($count / $pageSize);
        $list   = Db::name('order')
            ->where($where)
            ->field('id,order_id')
            ->select()
            ->toArray();

        foreach($list as $k=>$v){
            (new TestLogic())->test_hwc_order($v);
            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$k.'页' . PHP_EOL;
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }


    public function change_skus($skus){
        try{
            $skus  = explode(',',$skus);
            $arr   = [];
            foreach($skus as $value){
                if(strpos($value, '+') !== false){
                    $skuInfo    = get_shopify_spu($value,1);
                }else{
                    $skuInfo = $value;

                }
                if(strlen($skuInfo)<10){
                    continue;
                }
                $skuInfo = explode(',',$skuInfo);
                foreach($skuInfo as $v1){
                    $skus  = (new TestLogic())->get_sku_num_jxc($v1);
                    $temp['sku']  = $skus['sku']??'';
                    $temp['nums'] = $skus['num']??'';
                    $arr[] =$temp;
                }
            }
            return  $arr;
        }catch(\Exception $e) {
            echo  $e->getMessage();
            return error('失败:' . $e->getMessage());
        }

    }


    public function change_weight1(){
        $t1            = microtime(true);
        $where         = [];
        $list          = Db::name('conversations')->field('id,created_at')->where($where)->select()->toArray();
        $executedCount = 0;
        $count         = count($list);
        try{
            foreach ($list as $k=>$v){
                echo PHP_EOL ."执行第:" . ($k+1) ."条".PHP_EOL;
                $sku_info   =  explode(',',$v['need_sku_info']);
                $arrs = [];
                if($sku_info){
                    foreach($sku_info as $value){
                        $skus = (new TestLogic())->get_sku_num_jxc($value);
                        $temp['sku'] = $skus['sku']??'';
                        $temp['nums'] = $skus['num']??'';
                        $arrs[] = $temp;
                    }
                }
                Db::name('checkbill_999')->insertAll($arrs);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
            }
            echo PHP_EOL . "get_spu_fee-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        }catch (\Exception $e) {
            echo  $e->getMessage();
            return error('失败:' . $e->getMessage());
        }

    }

    public function change_weight2(){
        $list = Db::name('checkbill_999')->field('sum(nums) as number,sku')
            ->group('sku')
            ->select()->toarray();
        foreach($list as $v){
            Db::name('checkbill_777')->insert(
                [
                    'sku'=>$v['sku']??'',
                    'nums'=>$v['number']??'',
                ]
            );
        }
    }


    /**
     * @desc   获取token数据
     * @author xx
     * @date   2024-11-14
     */
    public function get_google_token($params=[]){

        $code_verifier     = $params['code_verifier']??'';
        $authorizationCode = $params['authorization_code']??'';
        $google_info       = Config('Logisticskey.google_info');
        $clientId          = $google_info['client_id'];
        $clientSecret      = $google_info['client_secret'];
        $redirectUri       = $google_info['redirect_url'];
        $tokenUrl          = $google_info['token_url'];
        $postData = [
            'code'          => $authorizationCode,
            'client_id'     => $clientId,
            'client_secret' => $clientSecret,
            'redirect_uri'  => $redirectUri,
            'grant_type'    => 'authorization_code',
            'code_verifier' => $code_verifier,
        ];
        $info =  HttpUtil::doPost($tokenUrl,$postData);
        if(isset($info['refresh_token'])){
            $refresh_token   = str_replace(' ', '', $info['refresh_token']);
            $update_data = [
                'access_token'  => $info['access_token']??'',
                'refresh_token' => $refresh_token,
                'create_time'   => date("Y-m-d H:i:s", time()),
                'expire_time'   => date("Y-m-d H:i:s", time()+3600-10),
            ];
            $exist_info = Db::name('google_ads_token')->find();
            if(!$exist_info){
                Db::execute('TRUNCATE TABLE qu_google_ads_token');
            }
            Db::name('google_ads_token')->insert($update_data);
        }
        return  $info;
    }


    /**
     * @desc   获取code数据
     * @author xx
     * @date   2024-11-14
     */
    public function get_authorization_code(){
        $codeVerifier  = generateRandomString(); // 生成 code_verifier
        $codeChallenge = base64url_encode(hash('sha256', $codeVerifier, true));
        $google_info   = Config('Logisticskey.google_info');
        $clientId      = $google_info['client_id'];
        $redirectUri   = $google_info['redirect_url'];

        // 打印生成的 code_verifier 和 code_challenge
        $authUrl = 'https://accounts.google.com/o/oauth2/auth?response_type=code' .
            '&client_id=' . $clientId .
            '&redirect_uri=' . $redirectUri .
            '&scope=' . urlencode('https://www.googleapis.com/auth/adwords') .
            '&code_challenge=' . $codeChallenge .
            '&code_challenge_method=S256' .
            '&access_type=offline';
        return [
            'code_verifier'    =>$codeVerifier,
            'code_challenge'   =>$codeChallenge,
            'code_redirect_url'=>filter_var($authUrl, FILTER_SANITIZE_URL),
        ];
    }


    /**
     * @desc   获取token数据
     * @author xx
     * @date   2024-11-15
     */
    public function get_access_token($params=[]){
        $google_info       = Config('Logisticskey.google_info');
        $refresh_token_url = $google_info['refresh_token_url'];
        $list              = Db::name('google_ads_token')->field('id,shop_id,refresh_token')->select()->toArray();
        foreach($list as $v){
            $client_info       = self::get_client_info($v['shop_id']);
            $clientId          = $client_info['client_id'];
            $clientSecret      = $client_info['client_secret'];
            $refresh_token     = $v['refresh_token'];
            $postData = [
                'client_id'     => $clientId,
                'client_secret' => $clientSecret,
                'refresh_token' => $refresh_token,
                'grant_type'    => 'refresh_token',
            ];
            $info  =  HttpUtil::postDataCurl($refresh_token_url,$postData);
            if(isset($info['access_token'])){
                $update_data = [
                    'access_token'  => $info['access_token']??'',
                    'expire_time'   => date("Y-m-d H:i:s", time()+3600-10),
                ];
                Db::name('google_ads_token')->where(['id'=>$v['id']])->update($update_data);
            }
        }

        return 1;
    }


    private function get_client_info($shop_id){
        $google_info       = Config('Logisticskey.google_info');
        if($shop_id == 21){
            $google_info    = Config('Logisticskey.google_info_21');
        }
        return ['client_id'=>$google_info['client_id'],'client_secret'=>$google_info['client_secret']];
    }



    /**
     * @desc   谷歌账户拉取某一天的数据
     * @author xx
     * @date   2024-11-15
     */
    public function updateCostMicros($params=[]){
        $date = $params['date']??'';
        $customer_ids = Config('Logisticskey.google_info.customer_ids');
        foreach($customer_ids as $v){
            $arr[] = self::get_spend($date,$v);
        }
        return ['spend'=>getRes(array_sum($arr)/1000000)];
    }


    /**
     * @desc   谷歌账户拉取某一天的数据
     * @author xx
     * @date   2024-11-15
     */
    public function get_spend($date_start_gg,$advertiser_id_gg){
        $query = 'SELECT campaign.name, campaign.status, segments.device,
                    metrics.impressions, metrics.clicks, metrics.ctr,
                    metrics.average_cpc, metrics.cost_micros,
                    metrics.active_view_measurable_cost_micros
            FROM campaign
            WHERE metrics.cost_micros>0 and segments.date BETWEEN "'.$date_start_gg.'" AND "'.$date_start_gg.'"';

        $data = [
            'query' => $query,
        ];
        $google_ads_token = Db::name('google_ads_token')->where('id',1)->value('access_token');
        $iscustom['access_token'] = $google_ads_token;
        $iscustom['developer_token'] = Config('Logisticskey.google_info.api_token') ?? "";
        $iscustom['login_customer_id'] = Config('Logisticskey.google_info.ads_id') ?? "";
        $url = Config('Logisticskey.google_info.customers_url').'/'.$advertiser_id_gg.'/googleAds:searchStream';
        $return = HttpUtil::postUrlgg($url, $data,$iscustom);
        $results    = $return[0]['results'] ?? [];
        $costMicros = 0;
        if($results){
            foreach ($results as $v) {
                $costMicros += $v['metrics']['costMicros'] ?? 0;
            }
        }
        return $costMicros;
    }

    /**
     * @desc   谷歌账账户费用
     * @author xx
     * @date   2024-12-09
     */
    private function get_google_spend($advertiser_id_gg,$date_start_gg,$adver_id){
        $query = 'SELECT campaign.name, campaign.status, segments.device,
                    metrics.impressions, metrics.clicks, metrics.ctr,
                    metrics.average_cpc, metrics.cost_micros,
                    metrics.active_view_measurable_cost_micros
            FROM campaign
            WHERE metrics.cost_micros>0 and segments.date BETWEEN "'.$date_start_gg.'" AND "'.$date_start_gg.'"';

        $data = [
            'query' => $query,
        ];
        $iscustom   = self::get_google_client($advertiser_id_gg);
        $url    = Config('Logisticskey.google_info.customers_url').'/'.$advertiser_id_gg.'/googleAds:searchStream';
        $return = HttpUtil::postUrlgg($url, $data,$iscustom);
        $results    = $return[0]['results'] ?? [];
        $costMicros = 0;

        if($results){
            foreach ($results as $v) {
                $costMicros += $v['metrics']['costMicros'] ?? 0;
            }
        }
        $spend            = $costMicros ? getRes($costMicros/1000000) : '';
        $stat_time_day    = $date_start_gg . ' 00:00:00';
        $update_arr = [
            'spend'             => $spend,
            'createtime'        => time(),
        ];
        if(empty($results)){
            $update_arr['error'] = json_encode($return);
        }
        //更新广告表;
        Db::name('advertising')->where(['advertiser_id'=>$adver_id,'stat_time_day'=>$stat_time_day])->update($update_arr);
        return true;
    }


    /**
     * @desc   google账户获取token
     * @author xx
     * @date   2024-11-15
     */
    private function get_google_client($advertiser_id_gg){
        $google_ids    = Config('Logisticskey.google_info_21.customer_ids');
        $google_info   = Config('Logisticskey.google_info');
        $google_ads_token = Db::name('google_ads_token')->where('id',1)->value('access_token');
        if(in_array($advertiser_id_gg,$google_ids)){
            $google_ads_token = Db::name('google_ads_token')->where('id',2)->value('access_token');
            $google_info      = Config('Logisticskey.google_info_21');
        }
        $iscustom['access_token']      = $google_ads_token;
        $iscustom['developer_token']   = $google_info['api_token'] ?? "";
        $iscustom['login_customer_id'] = $google_info['ads_id']?? "";
        return $iscustom;
    }




    /**
     * @desc   FB账户拉取某一天的数据
     * @author xx
     * @date   2024-11-15
     */
    public function updateFbCost($params=[]){
        $dateString = $params['date']??'';
        $date       = substr($dateString, 0, 4) . '-' . substr($dateString, 4, 2) . '-' . substr($dateString, 6, 2);
        //获取FB在用的广告账户数据;
        $where     = [];
        $where[]   = ['status','=','1'];
        $where[]   = ['platform_id','=','1'];
        $title     = 'shecurve';
        $where[]   =  ['info', 'like', '%' . $title . '%'];
        $customer_list= Db::name('advaccount')->field('id,advertiser_id')->where($where)->select()->toArray();

        $arr          = [];
        foreach($customer_list as $v){
            $arr[] = self::get_fb_cost($v['advertiser_id'],$date);
        }
        return ['spend'=>getRes(array_sum($arr))];
    }


    /**
     * @desc   FB账户拉取某一天的数据
     * @author xx
     * @date   2024-11-15
     */
    public function updateTikCost($params){
        $dateString = $params['date']??'';
        $date       = substr($dateString, 0, 4) . '-' . substr($dateString, 4, 2) . '-' . substr($dateString, 6, 2);
        //获取tik在用的广告账户数据;
        $where     = [];
        $where[]   = ['status','=','1'];
        $where[]   = ['platform_id','=','3'];
        $customer_list= Db::name('advaccount')->field('id,advertiser_id')->where($where)->select()->toArray();
        $arr      = [];
        foreach($customer_list as $v){
            $arr[] = self::get_tik_cost($v['advertiser_id'],$date);
        }
        return ['spend'=>getRes(array_sum($arr))];
    }



    /**
     * @desc   FB账户拉取某一天的数据
     * @author xx
     * @date   2024-11-15
     */
    public function get_fb_cost($advertiser_id, $date){
        $date_start         = $date;
        $fb_token           = Db::name('fb_token')->where('access_token',"<>","")->find();
        $token              = $fb_token['access_token'];
        $path               = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.'act_'.$advertiser_id.'/insights?access_token='.$token.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        return  $return['data'][0]['spend']??'';
    }


    /**
     * @desc   FB账户拉取某一天的数据
     * @author xx
     * @date   2025-04-15
     */
    public function get_fb_price($advertiser_id, $date){
        $date_start         = $date;
        $fb_token           = Db::name('fb_token')->where('access_token',"<>","")->find();
        $token              = $fb_token['access_token'];
        $path               = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.'act_'.$advertiser_id.'/insights?access_token='.$token.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
        $return = HttpUtil::getUrlFB($url);
        return json_decode($return,true);
    }




    /**
     * @desc    刷新fb的token信息
     * @date    2025-02-12
     * @author  xx
     */
    public function refreshAccessToken($currentToken) {
        $params = [
            "grant_type"        => "fb_exchange_token",
            "client_id"         => Config('Logisticskey.Facebookad.client_id'),
            "client_secret"     => Config('Logisticskey.Facebookad.client_secret'),
            "fb_exchange_token" => $currentToken
        ];
        $path                   = Config('Logisticskey.Facebookad.refresh_token');
        $url                    = $path . '?' . http_build_query($params);
        $response               = file_get_contents($url);
        p($response);die;
        return json_decode($response, true);
    }


    public function track_4px_sign($track_number){
        $microtime               = microtime(true);
        // 将微秒转换为毫秒
        $milliseconds            = round($microtime * 1000);
        // 输入的基本参数
        $params = [
            'app_key'   =>  Config('Logisticskey.4px_track.app_key'),
            'format'    => 'json',
            'method'    => Config('Logisticskey.4px_track.track_method'),
            'timestamp' => $milliseconds, // 当前时间戳，毫秒
            'v'         => '1.0.0',
            'body'      => json_encode(['deliveryOrderNo' => $track_number]), // 将 body 序列化为 JSON 字符串
        ];
        $app_secret = Config('Logisticskey.4px_track.app_secret');
       // 将参数拼接成签名字符串
        $signStr =
            'app_key' . $params['app_key'] .
            'format' . $params['format'] .
            'method' . $params['method'] .
            'timestamp' . $params['timestamp'] .
            'v' . $params['v'] .
            $params['body'] . // 使用序列化后的 JSON
            $app_secret; // 最后加上 App Secret
        // 计算 MD5 签名
        $generatedSign = md5($signStr);
        return ['signature'=>$generatedSign,'timestamp'=>$milliseconds];
    }



    public function track_4px($params=[]){
        $url                  = Config('Logisticskey.4px_track.url');
        $param  = [
            'method'          => Config('Logisticskey.4px_track.track_method'),
            'app_key'         => Config('Logisticskey.4px_track.app_key'),
            'v'               => '1.0.0',
        ];
        $track_number     = $params['track_number']??'';
        $signature_info   =  self::track_4px_sign($track_number);
        $param['timestamp'] =  $signature_info['timestamp'];
        $param['format']    =  'json';
        $param['sign']      =  $signature_info['signature'];
        $data             = [
            'deliveryOrderNo'=>$track_number
        ];
        $signature_url      = urladdparam($url,$param);
        $post               = HttpUtil::postDataCurl($signature_url,$data);
        $track_number       = $post['data']['deliveryOrderNo']??'';
        $tracking_list      = $post['data']['trackingList']??[];
        //接收地址;
        $recipient_address  = $post['data']['destinationCountry']??'US';
        $status_17_staus    = Config('Logisticskey.4px_track.4px_17_status');
        //最新的物流主状态;
        $current_info       =  current($tracking_list);
        $result             =  $current_info['businessLinkCode']??'';
        $latest_status      =  $status_17_staus[$result]??'';
        $exist_info         = Db::name('order_track')->field('id,order_id,latest_status,shop_id,track_number')->where(['track_number'=>$track_number])->find();
        if(isset($exist_info['latest_status']) && $exist_info['latest_status'] == 'Delivered'){
           // return true;
        }
        //最新物流子状态;
        $latest_sub_status  =  $result;

        //发送提供的物流商和国家;
        $tracking_provider_country = $post['data']['originCountry']??'CN';
        $tracking_provider_name    = '';

        //tracking数组;
        $tracking_info             = [];



        if($tracking_list){
            foreach($tracking_list as $v){
                $temp['time_raw']    = $v['occurDatetime'];
                $temp['location']    = '';
                $temp['description'] = $v['trackingContent'];
                $temp['sub_status']  = $v['businessLinkCode']??'';
                $tracking_info[]     = $temp;
            }
        }

        $insert_data =  [
            'track_number'     =>$track_number,
            'provider_country' =>$tracking_provider_country,
            'provider_name'    =>$tracking_provider_name,
            'receive_country'  =>$recipient_address,
            'latest_status'    =>$latest_status,
            'latest_sub_status'=>$latest_sub_status,
            'platform_track'   =>2,
            'tracking_list'    =>$tracking_info ? json_encode($tracking_info) : '',
            'update_time'      =>date("Y-m-d H:i:s", time()),
            'create_time'      =>date("Y-m-d H:i:s", time()),
        ];

        $update_data = [
            'track_number'     =>$track_number,
            'provider_country' =>$tracking_provider_country,
            'provider_name'    =>$tracking_provider_name,
            'receive_country'  =>$recipient_address,
            'latest_status'    =>$latest_status,
            'latest_sub_status'=>$latest_sub_status,
            'platform_track'   =>2,
            'tracking_list'    =>$tracking_info ? json_encode($tracking_info) : '',
            'update_time'      =>date("Y-m-d H:i:s", time()),
        ];

        $ApiOrderLogic = new ApiOrderLogic();
        if(empty($exist_info)){
            $order_info = Db::name('order')->field('id,order_id,shop_id')->where(['tracking_number'=>$track_number])->find();
            $insert_data['order_id'] = $order_info['order_id']??'';
            $insert_data['shop_id']  = $order_info['shop_id']??'';
            Db::name('order_track')->insert($insert_data);
            //修改配送状态--先关闭
            $ApiOrderLogic->updateOrderLogisticsStatus($insert_data);
        }else{
            Db::name('order_track')->where(['id'=>$exist_info['id']])->update($update_data);
            //修改配送状态--先关闭
            $ApiOrderLogic->updateOrderLogisticsStatus($insert_data);
        }

        //更新订单表物流在途状态
        Db::name('order')
            ->where('tracking_number', $track_number)
            ->update(['LogisticsStatus' => $latest_status]);

        Db::name('order_achievement')
            ->where('tracking_number', $track_number)
            ->update(['LogisticsStatus' => $latest_status]);

        return true;
    }





    /**
     * @desc   FB账户拉取某一天的数据
     * @author xx
     * @date   2024-12-11
     */
    private function get_tik_cost($advertiser_id,$date){
        $path               = Config('Logisticskey.tiktokad.path');
        $integratedget      = Config('Logisticskey.tiktokad.integratedget');
        $access_token       = Config('Logisticskey.tiktokad.access_token');
        $end_date           = date('Y-m-d', strtotime($date) + 1 * 24 * 3600);
        $dimensions         = ['advertiser_id', 'stat_time_day'];
        $dimensions         = json_encode($dimensions, true);
        $url                = $path."".$integratedget."/?advertiser_id=".$advertiser_id."&page=1&data_level=AUCTION_ADVERTISER&report_type=BASIC&dimensions=".$dimensions."&page_size=1000&start_date=".$date."&end_date=".$end_date;
        $return             = HttpUtil::getUrlTk($url, $access_token);
        $return             = json_decode($return, true);
        $results            = $return['data']['list'] ?? [];
        $costMicros         = 0;
        if($results){
            foreach ($results as $v) {
                $costMicros += $v['metrics']['spend'] ?? 0;
            }
        }
        return $costMicros;
    }

    /**
     * @desc   FB账户花费获取
     * @author xx
     * @date   2024-12-09
     */
    private function get_fb_spend($advertiser_id,$date){
        $date_start         = $date;
        $fb_token           = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token              = $fb_token['access_token'];
        $path               = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.'act_'.$advertiser_id.'/insights?access_token='.$token.'&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_start.'"}&appsecret_proof='.$appsecret_proof;
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        $spend  = $return['data'][0]['spend']??'';
        $stat_time_day    = $date . ' 00:00:00';
        $update_arr = [
            'spend'             => $spend,
            'createtime'        => time(),
        ];
        if(empty($spend)){
            $update_arr['error'] = json_encode($return);
        }
        //更新广告表;
        Db::name('advertising')->where(['advertiser_id'=>$advertiser_id,'stat_time_day'=>$stat_time_day])->update($update_arr);
        return true;
    }




    /**
     * @desc   tik账户花费获取
     * @author xx
     * @date   2024-12-09
     */
    private function get_tik_spend($advertiser_id,$date){
        $path               = Config('Logisticskey.tiktokad.path');
        $integratedget      = Config('Logisticskey.tiktokad.integratedget');
        $access_token       = Config('Logisticskey.tiktokad.access_token');
        $end_date           = date('Y-m-d', strtotime($date) + 1 * 24 * 3600);
        $dimensions         = ['advertiser_id', 'stat_time_day'];
        $dimensions         = json_encode($dimensions, true);
        $url                = $path."".$integratedget."/?advertiser_id=".$advertiser_id."&page=1&data_level=AUCTION_ADVERTISER&report_type=BASIC&dimensions=".$dimensions."&page_size=1000&start_date=".$date."&end_date=".$end_date;
        $return             = HttpUtil::getUrlTk($url, $access_token);
        $return             = json_decode($return, true);
        $results            = $return['data']['list'] ?? [];
        $costMicros         = 0;
        if($results){
            foreach ($results as $v) {
                $costMicros += $v['metrics']['spend'] ?? 0;
            }
        }
        $spend            = $costMicros ? getRes($costMicros) : '';
        $stat_time_day    = $date . ' 00:00:00';
        $update_arr = [
            'spend'             => $spend,
            'createtime'        => time(),
        ];
        if(empty($results)){
            $update_arr['error'] = json_encode($return);
        }
        //更新广告表;
        Db::name('advertising')->where(['advertiser_id'=>$advertiser_id,'stat_time_day'=>$stat_time_day])->update($update_arr);
        return true;
    }



    /**
     * @desc    广告数据初始记录定时写入，每天下午3点执行
     * @author  xx
     * @date    2024-12-05
     */
    public function insert_day_advertise($params=[])
    {
        $stat_time_day = updatetime_automatic_format();
        $google_adver_ids = Config('Logisticskey.google_info.google_adver_ids');
        $where   = [];
        $where[] = ['status', '=', '1'];
        $where[] = ['platform_id', 'in', [1,3]];
        $customer_list = Db::name('advaccount')->field('id,advertiser_id')->where($where)->select()->toArray();
        $customer_list = array_column($customer_list, 'advertiser_id');
        $adver_ids     = array_merge($customer_list, $google_adver_ids);
        $insert_arr    = [];
        foreach($adver_ids as $k=>$v){
            if(strpos($v,'-')){
                $platform_id = 2; //google
            }else{
                if(strlen($v)<19){ //fb
                    $platform_id = 1;
                }else{  //tik
                    $platform_id = 3;
                }
            }
            $insert_arr[$k]['advertiser_id'] = $v;
            $insert_arr[$k]['stat_time_day'] = $stat_time_day;
            $insert_arr[$k]['platform_id']   = $platform_id;
            $insert_arr[$k]['stat_time']     = time();
            $insert_arr[$k]['createtime']    = time();
        }
        Db::name('advertising')->insertAll($insert_arr);
        $num = count($insert_arr);
        return $stat_time_day.'写入初始广告账户数据'.$num.'条';
    }

    /**
     * @desc   广告需要跑数据的生产方法
     * @author xx
     * @date   2024-12-09
     */
    public function day_advertise_produce(){
        $date = updatetime_automatic();
        $google_adver_ids = Config('Logisticskey.google_info.google_adver_ids');
        $where = [];
        $where[] = ['status', '=', '1'];
        $where[] = ['platform_id', 'in', [1,3]];
        $customer_list = Db::name('advaccount')->field('id,advertiser_id')->where($where)->select()->toArray();
        $customer_list = array_column($customer_list, 'advertiser_id');
        $adver_ids     = array_merge($customer_list, $google_adver_ids);
        foreach($adver_ids as $v){
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_ADVERTISE_COST_QUEUE,
                [
                    'advertiser_id'=>$v,
                    'date'         =>$date,
                ],
                false
            );
        }
        $num = count($adver_ids);
        return '广告需要跑数据'.$num.'条';
    }


    /**
     * @desc   拉取某一天的FB和GOOGLE的数据
     * @author xx
     * @date   2024-11-15
     */
    public function get_advertise_consumer($message){
        $date          = $message['date']??'';
        $adver_id      = $message['advertiser_id']??'';
        if(!$date || !$adver_id) return ['msg'=>'入参为空!'];
        if(strpos($adver_id,'-')){
            $advertiser_id= str_replace("-", "", $adver_id);
            //google 花费获取;
            self::get_google_spend($advertiser_id,$date,$adver_id);
        }else{
            if(strlen($adver_id)<19){
                $advertiser_id = $adver_id;
                //fb花费获取;
                self::get_fb_spend($advertiser_id,$date);
            }else{
                $advertiser_id = $adver_id;
                //tik花费获取;
                self::get_tik_spend($advertiser_id,$date);
            }
        }
        return  true;
    }



    /**
     * @desc    获取某个店铺的ROI数据
     * @author  luckyXiong
     * @date    2025-01-06
     */
    public function getShopRoi($params=[]){
        $dateString = $params['date']??'';
        $date       = substr($dateString, 0, 4) . '-' . substr($dateString, 4, 2) . '-' . substr($dateString, 6, 2);
        $where      = [];
        $where[] = ['a.createtime', '>=', strtotime($date)];
        $where[] = ['a.createtime', '<=', strtotime($date) + 3600*24-1];
        $where[]       = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]       = ['a.shop_id','=',21];
        $list = Db::name('order_achievement')
            ->field('COUNT(a.id) as quantity,sum(a.total_price) as total_price, sum(a.skuquantity) as skuquantity,sum(a.old_total_price) as old_total_price')
            ->alias('a')
            ->where($where)
            ->group('a.shop_id')
            ->select();
        $list = objectToArray($list);
        if(!$list)   return [];
        $roi_total = 0;
        $advertising_total = 0;
        $total_price_total = 0;
        if($list){
            foreach ($list as &$v) {
                $v['total_price'] = $v['old_total_price'];
                $v['advertising'] = $this->advertising_campaign(21,$date);
                //ROI
                if ($v['advertising'] > 0.001 && $v['total_price'] > 0.001) {
                    $v['roi'] = number_format((float)$v['total_price'] / (float)$v['advertising'], 2, '.', '');
                }else{
                    $v['roi'] = 0;
                }
                //计算ROI
                $advertising_total += (float)$v['advertising'];
                $total_price_total += (float)$v['total_price'];
                $v['skuquantity'] = (int)$v['skuquantity'];
            }
            //计算ROI
            if ($advertising_total > 0.001 && $total_price_total > 0.001) {
                $roi_total = number_format((float)$total_price_total / (float)$advertising_total, 2, '.', '');
            }else{
                $roi_total = 0;
            }
        }
        $current = current($list);
        $data = [
            'sales_total'              =>  $current['total_price']??'',
            'advertising_spend'        =>  getRes($advertising_total),
            'roi'                      =>  $roi_total,
        ];
        return $data;
    }


    /**
     * @desc    获取kisslove店铺的ROI数据
     * @author  luckyXiong
     * @date    2025-01-06
     */
    public function getkissloveShop($params=[]){
        $dateString = $params['date']??'';
        $date       = substr($dateString, 0, 4) . '-' . substr($dateString, 4, 2) . '-' . substr($dateString, 6, 2);
        $where      = [];
        $shop_id    = 22;
        $where[] = ['a.createtime', '>=', strtotime($date)];
        $where[] = ['a.createtime', '<=', strtotime($date) + 3600*24-1];
        $where[]       = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]       = ['a.shop_id','=',$shop_id];
        $list = Db::name('order_achievement')
            ->field('COUNT(a.id) as quantity,sum(a.total_price) as total_price, sum(a.skuquantity) as skuquantity,sum(a.old_total_price) as old_total_price')
            ->alias('a')
            ->where($where)
            ->group('a.shop_id')
            ->select();
        $list = objectToArray($list);
        if(!$list)   return [];
        $roi_total = 0;
        $advertising_total = 0;
        $total_price_total = 0;
        if($list){
            foreach ($list as &$v) {
                $v['total_price'] = $v['old_total_price'];
                $v['advertising'] = $this->advertising_campaign($shop_id,$date);
                //ROI
                if ($v['advertising'] > 0.001 && $v['total_price'] > 0.001) {
                    $v['roi'] = number_format((float)$v['total_price'] / (float)$v['advertising'], 2, '.', '');
                }else{
                    $v['roi'] = 0;
                }
                //计算ROI
                $advertising_total += (float)$v['advertising'];
                $total_price_total += (float)$v['total_price'];
                $v['skuquantity'] = (int)$v['skuquantity'];
            }
            //计算ROI
            if ($advertising_total > 0.001 && $total_price_total > 0.001) {
                $roi_total = number_format((float)$total_price_total / (float)$advertising_total, 2, '.', '');
            }else{
                $roi_total = 0;
            }
        }
        $current = current($list);
        $data = [
            'sales_total'              =>  $current['total_price']??'',
            'advertising_spend'        =>  getRes($advertising_total),
            'roi'                      =>  $roi_total,
        ];
        return $data;
    }


    /**
     * @desc   发送邮件消息
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function send_email($params){
        $date_zone_start = $params['date_zone_start']??'';
        $date_zone_end   = $params['date_zone_end']??'';
        $message         = $params['message']??'';
        $shop_id         = $params['shop_id']??'';
        $update_id       = $params['update_id']??'';
        $shop_name       = self::get_brand($shop_id);

        $where           = [];

        $where[]         = ['update_type','=',0];
        $where[]         = ['status','=',0];
        $where[]         = ['channel','=',1];
        $where[]         = ['brand','=',$shop_name];
        $where[]         = ['order_time','<>',''];
        $where[]         = ['order_time','between', [$date_zone_start, $date_zone_end]];

        $count =  Db::name('conversations')
            ->field('id,brand,slug')
            ->where($where)
            ->count();

        $pageSize      = 600;
        $page          = ceil($count / $pageSize);
        for ($i = 0; $i <= $page; $i++){
            $list = Db::name('conversations')
                ->field('id,brand,slug')
                ->where($where)
                ->order('order_time asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            if(!$list)   return  $this->jsonMessage(201,false,'暂无数据',null);
            //推送数据到队列;
            foreach($list as $v){
                //推动数据到队列;
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_EMAIL_REPLY_QUEUE,
                    [
                        'brand'   =>$shop_name,
                        'slug'    =>$v['slug'],
                        'message' =>$message,
                        'id'      =>$v['id'],
                    ],
                    false
                );
            }
        }

        //更新执行的总数量;
        Db::name('customer_email_log')->where('id',$update_id)->update(
            [
                'status'=>1,
                'nums'  =>$count,
            ]
        );
        return  $this->jsonMessage(200,true,'操作成功',null);
    }

    /**
     * @desc   新增标签
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function add_tag($params){
        $date_zone_start = $params['date_zone_start']??'';
        $date_zone_end   = $params['date_zone_end']??'';
        $tag             = $params['tag']??'';
        $shop_id         = $params['shop_id']??'';
        $update_id       = $params['update_id'];
        $nums            = $params['nums'];
        $shop_name       = self::get_brand($shop_id);
        $tags            = Config('Logisticskey.emial_tags');
        if(!in_array($tag,$tags)){
            return  $this->jsonMessage(200,true,'标签不在规则范围内',null);
        }
        $tag_new = [$tag];
        $pageSize = $nums;
        if($tag == "ALL"){
            $tag_new  = $tags;
            $pageSize = ceil($nums / 14);
        }
        $page     = count($tag_new);
        for ($i = 0; $i < $page; $i++){
            $list = Db::name('conversations')
                ->field('id,brand,slug')
                ->where('tags_type',0)
                ->where('status',0)
                ->where('channel',1)
                ->where('brand',$shop_name)
                ->where('created_at',">=",$date_zone_start)
                ->where('created_at',"<=",$date_zone_end)
                ->order('created_at asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            if(!$list)   return  $this->jsonMessage(201,false,'暂无数据',null);
            $update_tag = $tag_new[$i];
            //推送数据到队列;
            foreach($list as $v){
                //推动数据到队列;
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_EMAIL_TAG_QUEUE,
                    [
                        'brand'   =>$shop_name,
                        'slug'    =>$v['slug'],
                        'tag'     =>$update_tag,
                        'id'      =>$v['id'],
                        'type'    =>'add',
                    ],
                    false
                );
            }
        }

        //更新执行的总数量;
        Db::name('customer_email_add')->where('id',$update_id)->update(
            [
                'status'=>1
            ]
        );
        return  $this->jsonMessage(200,true,'操作成功',null);
    }

    /**
     * @desc   删除标签
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function del_tag($params){
        $tag             = $params['tag']??'';
        $shop_id         = $params['shop_id']??'';
        $update_id       = $params['update_id'];
        $shop_name       = self::get_brand($shop_id);

        $tags = Config('Logisticskey.emial_tags');
        if(!in_array($tag,$tags)){
            return  $this->jsonMessage(200,true,'标签不在规则范围内',null);
        }
        $tag_new = [$tag];

        if($tag == "ALL"){
            $tag_new = $tags;
        }

        $count = Db::name('conversations')
            ->where('brand',$shop_name)
            ->whereIn('tags',$tag_new)
            ->count();
        $pageSize     = 500;
        $page         = ceil($count / $pageSize);
        for ($i = 0; $i < $page; $i++){
            $list = Db::name('conversations')
                ->field('id,brand,slug')
                ->where('brand',$shop_name)
                ->whereIn('tags',$tag_new)
                ->order('created_at asc')
                ->limit($pageSize)
                ->select()
                ->toArray();
            if(!$list)   return  $this->jsonMessage(201,false,'暂无数据',null);
            //推送数据到队列;
            foreach($list as $v){
                //推动数据到队列;
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_EMAIL_TAG_QUEUE,
                    [
                        'brand'   =>$shop_name,
                        'slug'    =>$v['slug'],
                        'tag'     =>'',
                        'id'      =>$v['id'],
                        'type'    =>'del',
                    ],
                    false
                );
            }
        }
        //更新执行的总数量;
        Db::name('customer_email_del')->where('id',$update_id)->update(
            [
                'status'=>1,
                'nums'  =>$count,
            ]
        );
        return  $this->jsonMessage(200,true,'操作成功',null);
    }


    /**
     * @desc   批量创建退款订单
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function batch_refund_create($params)
    {
        $ids     = $params['ids']??'';
        $adminId = $params['adminId']??'';
        htmlLog(['params'=>$params],OPERATE_LOG . date('Ym') . '/batch_refund_creates/' . date('Ymd') . '.txt');
        $ids = is_array($ids) ? $ids : explode(',', $ids);
        $items = Db::name('customer_refunds')->field('id,order_id,order_number,is_part,shop_id,currency,refund_payment as amount')
                 ->whereIn('id', $ids)
                 ->select();
        $items = objectToArray($items);
        if (empty($items))  return  $this->jsonMessage(200,true,'暂无批量创建退款订单数据',null);
        $first_arr = [];
        //创建批次
        $batch_id = Db::name('customer_refunds_batch')->insertGetId(
            [
                'num' => count($items),
                'update_time' => date("Y-m-d H:i:s", time()),
                'create_time' => date("Y-m-d H:i:s", time()),
            ]);

        foreach ($items as $v) {
            $first_arr[] = [
                'batch_id'      =>$batch_id,
                'order_id'      =>$v['order_id'],
                'order_number'  =>$v['order_number'],
                'shop_id'       =>$v['shop_id'],
                'status'        =>1,
                'msg'           =>"创建中",
                'is_part'       =>$v['is_part'],
                'refund_payment'=>$v['amount'],
                'currency'      =>$v['currency'],
                'operate_id'    =>$adminId,
                'create_time'   =>date("Y-m-d H:i:s", time()),
            ];

            Db::name('customer_refunds')->where(['id'=>$v['id']])->update(
                [
                    'refund_status'=>1,
                    'update_time'  =>date("Y-m-d H:i:s", time()),
                ]
            );

            // 队列处理
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_ORDER_REFUND_QUEUE,
                [
                    'order_id'  =>$v['order_id'],
                    'shop_id'   =>$v['shop_id'],
                    'amount'    =>$v['amount'],
                    'currency'  =>$v['currency'],
                    'id'        =>$v['id'],
                    'operate_id'=>$adminId,
                    'batch_id'  =>$batch_id,
                ],
                false
            );
        }
        if($first_arr){
            Db::name('customer_refunds_log')->insertAll($first_arr);
        }
        return  $this->jsonMessage(200,true,'操作成功','');
    }



    //获取店铺
    private function get_brand($shop_id){
        switch ($shop_id) {
            case '17':
                $shop_name = 'SheCurve';
                break;
            case '18':
                $shop_name = 'LilyLove';
                break;
            case '21':
                $shop_name = '4304ef';
                break;
            default:
                $shop_name = '';
                break;
        }
        return  $shop_name;
    }


    /**
     * @desc   更新海外仓库存
     * @author luckyXiong
     * @date   2025-04-08
     */
    public function update_hwc_inventory($params){
           $list = Db::name('inventory_hwc')->field('id,sku,warehouse_id')->select()->toArray();
           foreach($list as $v){
               // 队列处理
               MqTaskPushLogic::mq_task_push(
                   '',
                   MqQueueName::QUEUE_ORDER_HWC_INVENTORY_QUEUE,
                   $v,
                   false
               );
           }
           return  true;
    }


    /**
     * @desc   更新海外仓库存消费方法
     * @author luckyXiong
     * @date   2025-04-08
     */
    public function consumer_hwc_inventory($message){
        $base_url = Config('Logisticskey.YiJT.url');
        $url      = $base_url . Config('Logisticskey.YiJT.hwc_stock');
        $token    = Config('Logisticskey.YiJT.token');
        $warehouse_id  = $message['warehouse_id'];
        $ck_nums       =  Config('Logisticskey.YiJT.ck_nums');
        if($warehouse_id == 4){
            $ck_nums      =  Config('Logisticskey.YiJT.ck_nums2');
        }

        $info     = [
            'token'  => $token,
            'storage'=> $ck_nums,
            'sku'    => $message['sku'],
            'page'   => '1',
            'limit'  => '10',
        ];
        $response = HttpUtil::postUrlYiJT($url, $info);
        $response = json_decode($response, true);
        $info     = $response['data'][0]??[];
        $sku      = $info['ck_sku'];
        $nums     = $info['stock'];
        //查看订单是否存在;
        $exist_info = Db::name('inventory_hwc')->where(['sku'=>$sku,'warehouse_id'=>$warehouse_id])->find();
        if($exist_info){
            Db::name('inventory_hwc')->where(['id'=>$exist_info['id']])->update(
                [
                    'inventory_quantity'  =>$nums,
                    'created_time'        =>date("Y-m-d H:i:s", time()),
                    'new_quantity'        =>$nums,
                ]
            );
        }
        return true;
    }






    /**
     * @desc    获取某个店铺的ROI数据
     * @author  luckyXiong
     * @date    2025-01-06
     */
    public function advertising_campaign($shop_id,$date)
    {
        $date             = $date . ' 00:00:00';
        $where_campaign[] = ['a.shop_id', '=', $shop_id]; // 店铺id
        $where_campaign[] = ['a.stat_time_day', '=', $date]; // 店铺id

        $advertiser = Db::name('advertising')
            ->field('sum(a.spend) as spend')
            ->alias('a')
            ->where($where_campaign)
            ->order("spend desc")
            ->find();
        $advertising_spend = 0;
        if (!empty($advertiser['spend'])) {
            $advertising_spend = number_format((float)$advertiser['spend'], 2, '.', '');
        }
        return $advertising_spend;
    }


    /**
     * @desc    回复邮件消息
     * @author  luckyXiong
     * @date    2025-01-16
     */
    public function email_reply($info){

        $brand        = $info['brand'] ??'';
        $slug         = $info['slug'];
        $message      = $info['message'];
        $id           = $info['id'];
        if(!$brand || !$slug){
            return   true;
        }

        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        //邮箱搜索
        $url = 'https://'.$brand.'.reamaze.io/api/v1/conversations/'.$slug.'/messages';
        $data['message']['body'] = $message;
        $data['message']['visibility'] = 0;
        $data['message']['suppress_autoresolve'] = true;
        $data['message']['suppress_notifications'] = false;
        $res = HttpUtil::postUrlReamaze($url,$data, ['email' => $email, 'token' => $token]);
        htmlLog(['response'=>$res],OPERATE_LOG . date('Ym') . '/email_reply/' . date('Ymd') . '.txt');
        self::modifyTagsinfo($info,"replay");
        //更新标签字段;
        Db::name('conversations')->where('id',$id)->update([
            'update_type'=>1
        ]);
        return true;
    }

    //更新标签信息
    public function modifyTagsinfo($info,$tags)
    {
        $brand        = $info['brand']??'';
        $tags         = trim($tags);
        $slug         = $info['slug'];
        $type         = $info['type']??'';
        $tag_list     = [$tags];
        $email        = Config('Logisticskey.apireamaze.email');
        $token        = Config('Logisticskey.apireamaze.token');
        $url          = 'https://'.$brand.'.reamaze.io/api/v1/conversations/'.$slug;
        if($type=='del'){
            $tag_list = [];
        }
        $data['conversation']['tag_list'] = $tag_list;
        $res = HttpUtil::putUrlReamaze($url,$data, ['email' => $email, 'token' => $token]);
        htmlLog(['response'=>$res],OPERATE_LOG . date('Ym') . '/modifyTagsinfo/' . date('Ymd') . '.txt');
        return true;
    }


    /**
     * @desc    变更tag
     * @author  luckyXiong
     * @date    2025-01-16
     */
    public function email_tag($info){
        htmlLog(['params'=>$info],OPERATE_LOG . date('Ym') . '/email_tag/' . date('Ymd') . '.txt');
        $brand        = $info['brand'] ??'';
        $slug         = $info['slug']??'';
        $tag          = $info['tag']??'';
        $id           = $info['id'];
        $type         = $info['type'];
        if(!$brand || !$slug){
            return   true;
        }

        if($type=='add'){ //新增标签
            if(empty($tag)) return  true;
            $update['tags_type'] = 1;
            $update['tags']      = $tag;
        }else{ //删除标签
            $update['tags_type'] = 0;
            $update['tags']      = "";
        }
        $res = self::modifyTagsinfo($info,$tag);
        htmlLog(['response'=>$res],OPERATE_LOG . date('Ym') . '/email_tag/' . date('Ymd') . '.txt');
        //更新标签字段;
        Db::name('conversations')->where('id',$id)->update($update);
        return true;
    }











}